const Router = require('koa-router')
const { DynamicMenu, sequelize } = require('../models')
const auth = require('../middleware/auth')

const router = new Router({ prefix: '/api/dynamic-menu' })

// 获取所有菜单 - 根据用户权限过滤
router.get('/', auth.authenticateToken, async (ctx) => {
  try {
    const userPermissions = ctx.state.user.permissions || []
    
    const menus = await DynamicMenu.findAll({
      where: { status: 'active' },
      order: [['sort_order', 'ASC'], ['created_at', 'ASC']]
    })

    // 过滤用户有权限访问的菜单
    const filteredMenus = menus.filter(menu => {
      // 如果菜单没有设置权限要求，则所有用户都可以访问
      if (!menu.permissions || menu.permissions.length === 0) {
        return true
      }
      // 检查用户是否拥有菜单所需的任一权限
      return menu.permissions.some(permission => userPermissions.includes(permission))
    })

    ctx.body = {
      success: true,
      data: filteredMenus,
      message: '获取菜单列表成功'
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取菜单列表失败',
      error: error.message
    }
  }
})

// 创建新菜单
router.post('/', auth.checkPermission('system:manage'), async (ctx) => {
  try {
    const { name, key, icon, table_name, description, permissions, columns_config, sort_order } = ctx.request.body
    const created_by = ctx.state.user.userId

    // 检查key是否已存在
    const existingMenu = await DynamicMenu.findOne({ where: { key } })
    if (existingMenu) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '菜单标识已存在'
      }
      return
    }

    // 检查表是否存在
    const tableExists = await checkTableExists(table_name)
    if (!tableExists) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: `数据库表 ${table_name} 不存在`
      }
      return
    }

    const menu = await DynamicMenu.create({
      name,
      key,
      icon: icon || 'TableCellsIcon',
      table_name,
      description,
      permissions: permissions || ['read', 'create', 'update', 'delete'],
      columns_config,
      sort_order: sort_order || 0,
      created_by
    })

    ctx.body = {
      success: true,
      data: menu,
      message: '创建菜单成功'
    }
  } catch (error) {
    console.error('创建菜单失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '创建菜单失败',
      error: error.message
    }
  }
})

// 更新菜单
router.put('/:id', auth.checkPermission('system:manage'), async (ctx) => {
  try {
    const { id } = ctx.params
    const updateData = ctx.request.body

    const menu = await DynamicMenu.findByPk(id)
    if (!menu) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '菜单不存在'
      }
      return
    }

    // 如果更新表名，检查新表是否存在
    if (updateData.table_name && updateData.table_name !== menu.table_name) {
      const tableExists = await checkTableExists(updateData.table_name)
      if (!tableExists) {
        ctx.status = 400
        ctx.body = {
          success: false,
          message: `数据库表 ${updateData.table_name} 不存在`
        }
        return
      }
    }

    await menu.update(updateData)

    ctx.body = {
      success: true,
      data: menu,
      message: '更新菜单成功'
    }
  } catch (error) {
    console.error('更新菜单失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '更新菜单失败',
      error: error.message
    }
  }
})

// 删除菜单（软删除）
router.delete('/:id', auth.checkPermission('system:manage'), async (ctx) => {
  try {
    const { id } = ctx.params

    const menu = await DynamicMenu.findByPk(id)
    if (!menu) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '菜单不存在'
      }
      return
    }

    await menu.update({ status: 'inactive' })

    ctx.body = {
      success: true,
      message: '删除菜单成功'
    }
  } catch (error) {
    console.error('删除菜单失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '删除菜单失败',
      error: error.message
    }
  }
})


// 获取表数据
router.get('/table-data/:tableName', auth.authenticateToken, async (ctx) => {
  try {
    const { tableName } = ctx.params
    const { 
      page = 1, 
      limit = 20, 
      search = '', 
      sort_field = 'id', 
      sort_order = 'DESC',
      start_date,
      end_date,
      status 
    } = ctx.query
    const userPermissions = ctx.state.user.permissions || []

    // 验证表名安全性
    if (!isValidTableName(tableName)) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '无效的表名'
      }
      return
    }

    // 验证分页参数
    const pageNum = Math.max(1, parseInt(page))
    const limitNum = Math.min(100, Math.max(1, parseInt(limit))) // 限制最大100条
    const offset = (pageNum - 1) * limitNum

    // 验证排序字段安全性
    const allowedSortFields = ['id', 'created_at', 'updated_at', 'name', 'status']
    const sortField = allowedSortFields.includes(sort_field) ? sort_field : 'id'
    const sortOrderValue = ['ASC', 'DESC'].includes(sort_order.toUpperCase()) ? sort_order.toUpperCase() : 'DESC'

    const tableExists = await checkTableExists(tableName)
    if (!tableExists) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: `数据库表 ${tableName} 不存在`
      }
      return
    }

    // 临时简化权限检查 - 超级管理员跳过权限检查
    if (!userPermissions.includes('system:manage')) {
      console.log(`检查表 ${tableName} 的读取权限，用户权限:`, userPermissions)
      const hasReadPermission = await checkTablePermission(tableName, 'read', userPermissions)
      console.log(`权限检查结果:`, hasReadPermission)
      
      if (!hasReadPermission) {
        console.log(`用户没有访问表 ${tableName} 的权限`)
        ctx.status = 403
        ctx.body = {
          success: false,
          message: '您没有权限访问此数据表'
        }
        return
      }
    }
    
    // 构建查询条件
    let whereClauses = []
    let replacements = {}
    
    // 搜索条件 - 使用更安全的搜索方式
    if (search && search.trim()) {
      console.log(`执行搜索，关键词: "${search.trim()}"`)
      // 获取表的文本字段进行搜索
      const searchableFields = await getSearchableFields(tableName)
      console.log(`可搜索字段:`, searchableFields)
      if (searchableFields.length > 0) {
        const searchConditions = searchableFields.map(field => `${field} LIKE :search`).join(' OR ')
        whereClauses.push(`(${searchConditions})`)
        replacements.search = `%${search.trim()}%`
        console.log(`搜索条件: ${searchConditions}`)
      } else {
        console.log(`表 ${tableName} 没有可搜索的文本字段`)
      }
    }
    
    // 日期范围筛选
    if (start_date && end_date) {
      whereClauses.push(`(created_at >= :start_date AND created_at <= :end_date)`)
      replacements.start_date = start_date
      replacements.end_date = end_date + ' 23:59:59'
    }
    
    // 状态筛选
    if (status && ['active', 'inactive', 'pending'].includes(status)) {
      whereClauses.push(`status = :status`)
      replacements.status = status
    }
    
    const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : ''
    
    // 使用参数化查询防止SQL注入
    let countQuery = `SELECT COUNT(*) as total FROM \`${tableName}\`${whereClause}`
    let dataQuery = `SELECT * FROM \`${tableName}\`${whereClause} ORDER BY \`${sortField}\` ${sortOrderValue} LIMIT ${limitNum} OFFSET ${offset}`

    // 查询参数
    const queryParams = {
      replacements,
      type: sequelize.QueryTypes.SELECT
    }
    
    console.log(`执行查询 - 数据查询: ${dataQuery}`)
    console.log(`查询参数:`, replacements)
    
    // 并行执行查询提高性能
    const [countResult, data] = await Promise.all([
      sequelize.query(countQuery, queryParams),
      sequelize.query(dataQuery, queryParams)
    ])
    
    const total = countResult[0]?.total || 0

    ctx.body = {
      success: true,
      data: {
        list: data,
        pagination: {
          current: pageNum,
          pageSize: limitNum,
          total: total,
          pages: Math.ceil(total / limitNum)
        }
      },
      message: '获取表数据成功'
    }
  } catch (error) {
    console.error('获取表数据失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取表数据失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    }
  }
})

// 获取表结构
router.get('/table-structure/:tableName', auth.authenticateToken, async (ctx) => {
  try {
    const { tableName } = ctx.params
    const userPermissions = ctx.state.user.permissions || []

    const tableExists = await checkTableExists(tableName)
    if (!tableExists) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: `数据库表 ${tableName} 不存在`
      }
      return
    }

    // 检查用户是否有权限访问此表的菜单
    const menu = await DynamicMenu.findOne({ 
      where: { table_name: tableName, status: 'active' } 
    })
    
    if (menu && menu.permissions && menu.permissions.length > 0) {
      const hasPermission = menu.permissions.some(permission => userPermissions.includes(permission))
      if (!hasPermission) {
        ctx.status = 403
        ctx.body = {
          success: false,
          message: '您没有权限访问此数据表'
        }
        return
      }
    }

    // 获取表结构
    const [columns] = await sequelize.query(`DESCRIBE ${tableName}`)

    ctx.body = {
      success: true,
      data: {
        columns: columns.map(col => ({
          field: col.Field,
          type: col.Type,
          null: col.Null === 'YES',
          key: col.Key,
          default: col.Default,
          extra: col.Extra
        }))
      },
      message: '获取表结构成功'
    }
  } catch (error) {
    console.error('获取表结构失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取表结构失败',
      error: error.message
    }
  }
})

// 辅助函数：检查表是否存在
async function checkTableExists(tableName) {
  try {
    const [result] = await sequelize.query(`
      SELECT COUNT(*) as count 
      FROM INFORMATION_SCHEMA.TABLES 
      WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = :tableName
    `, {
      replacements: { tableName },
      type: sequelize.QueryTypes.SELECT
    })
    return result.count > 0
  } catch (error) {
    console.error('检查表是否存在失败:', error)
    return false
  }
}

// 辅助函数：验证表名安全性
function isValidTableName(tableName) {
  // 只允许字母、数字、下划线，防止SQL注入
  const validTablePattern = /^[a-zA-Z][a-zA-Z0-9_]*$/
  const allowedTables = [
    'products', 'customers', 'orders', 'users', 'roles', 'inventory', 
    'product_categories', 'order_items', 'permissions', 'table_configs',
    'table_themes', 'table_actions', 'table_columns', 'chat_histories',
    'ai_sql_logs', 'dynamic_menus', 'user_roles', 'role_permissions',
    'inventory_logs'
  ]
  return validTablePattern.test(tableName) && allowedTables.includes(tableName)
}

// 辅助函数：检查表权限
async function checkTablePermission(tableName, action, userPermissions) {
  try {
    // 如果用户有系统管理权限，直接通过
    if (userPermissions.includes('system:manage')) {
      return true
    }
    
    // 检查用户权限
    const resourceName = getResourceNameFromTable(tableName)
    const possiblePermissions = [
      `${resourceName}:${action}`,
      `table:${action}`,
      `${tableName}:${action}`,  // 直接表名权限
      `*:${action}`,              // 通配符权限
      '*'                         // 超级权限
    ]
    
    // 检查是否有任何匹配的权限
    const hasPermission = possiblePermissions.some(perm => userPermissions.includes(perm))
    if (hasPermission) return true
    
    // 检查动态菜单权限（仅作为额外检查）
    const menu = await DynamicMenu.findOne({ 
      where: { table_name: tableName, status: 'active' } 
    })
    
    // 如果没有菜单配置，允许访问（向后兼容）
    if (!menu) {
      return true
    }
    
    // 如果菜单没有设置权限要求，允许访问
    if (!menu.permissions || menu.permissions.length === 0) {
      return true
    }
    
    return false
  } catch (error) {
    console.error('检查表权限失败:', error)
    // 出错时允许访问，避免阻塞
    return true
  }
}

// 辅助函数：根据表名获取资源名
function getResourceNameFromTable(tableName) {
  const tableMap = {
    'products': 'product',
    'customers': 'customer', 
    'orders': 'order',
    'users': 'user',
    'roles': 'role',
    'inventory': 'inventory',
    'product_categories': 'product',
    'order_items': 'order',
    'permissions': 'permission',
    'table_configs': 'system',
    'table_themes': 'system',
    'table_actions': 'system',
    'table_columns': 'system',
    'chat_histories': 'chat',
    'ai_sql_logs': 'system',
    'dynamic_menus': 'system',
    'user_roles': 'user',
    'role_permissions': 'role',
    'inventory_logs': 'inventory'
  }
  return tableMap[tableName] || tableName
}

// 辅助函数：获取可搜索的字段
async function getSearchableFields(tableName) {

  try {

    const columns = await sequelize.query(`

      SELECT COLUMN_NAME 
      
      FROM INFORMATION_SCHEMA.COLUMNS 

      WHERE TABLE_SCHEMA = DATABASE() 

      AND TABLE_NAME = :tableName

      AND DATA_TYPE IN ('varchar', 'text', 'char', 'longtext', 'mediumtext')

      AND COLUMN_NAME NOT IN ('password', 'token', 'secret')

    `, {
      replacements: { tableName },
      type: sequelize.QueryTypes.SELECT
    })
    
    console.log(`表 ${tableName} 的可搜索字段:`, columns)
    return columns.map(col => `\`${col.COLUMN_NAME}\``)
  } catch (error) {
    console.error('获取可搜索字段失败:', error)
    return []
  }
}

// 辅助函数：验证和清理数据
async function validateAndSanitizeData(tableName, data, operation = 'create') {
  try {
    // 获取表结构
    const columns = await sequelize.query(`
      SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, CHARACTER_MAXIMUM_LENGTH
      FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = :tableName
    `, {
      replacements: { tableName },
      type: sequelize.QueryTypes.SELECT
    })

    const validatedData = {}
    const columnMap = {}
    columns.forEach(col => {
      columnMap[col.COLUMN_NAME] = col
    })

    // 验证每个字段
    for (const [key, value] of Object.entries(data)) {
      // 跳过系统字段
      if (['id', 'created_at', 'updated_at'].includes(key)) {
        continue
      }

      const column = columnMap[key]
      if (!column) {
        continue // 跳过不存在的字段
      }

      // 验证必填字段
      if (column.IS_NULLABLE === 'NO' && (value === null || value === undefined || value === '')) {
        if (!column.COLUMN_DEFAULT && key !== 'id') {
          throw new Error(`字段 ${key} 为必填项`)
        }
        continue
      }

      // 数据类型验证和转换
      let sanitizedValue = value
      
      if (column.DATA_TYPE.includes('int')) {
        sanitizedValue = parseInt(value)
        if (isNaN(sanitizedValue)) {
          throw new Error(`字段 ${key} 必须是数字`)
        }
      } else if (column.DATA_TYPE.includes('decimal') || column.DATA_TYPE.includes('float')) {
        sanitizedValue = parseFloat(value)
        if (isNaN(sanitizedValue)) {
          throw new Error(`字段 ${key} 必须是数字`)
        }
      } else if (column.DATA_TYPE.includes('varchar') || column.DATA_TYPE.includes('text')) {
        sanitizedValue = String(value).trim()
        if (column.CHARACTER_MAXIMUM_LENGTH && sanitizedValue.length > column.CHARACTER_MAXIMUM_LENGTH) {
          throw new Error(`字段 ${key} 长度不能超过 ${column.CHARACTER_MAXIMUM_LENGTH} 个字符`)
        }
        // 基本的XSS防护
        sanitizedValue = sanitizedValue.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
      } else if (column.DATA_TYPE.includes('date') || column.DATA_TYPE.includes('time')) {
        if (value && !isValidDate(value)) {
          throw new Error(`字段 ${key} 日期格式不正确`)
        }
        // 转换为 MySQL 格式
        if (value) {
          const date = new Date(value)
          if (column.DATA_TYPE.includes('datetime') || column.DATA_TYPE.includes('timestamp')) {
            sanitizedValue = date.toISOString().slice(0, 19).replace('T', ' ')
          } else {
            sanitizedValue = date.toISOString().slice(0, 10)
          }
        } else {
          sanitizedValue = value
        }
      }

      validatedData[key] = sanitizedValue
    }

    return validatedData
  } catch (error) {
    console.error('数据验证失败:', error)
    return null
  }
}

// 辅助函数：验证日期格式
function isValidDate(dateString) {
  const date = new Date(dateString)
  return date instanceof Date && !isNaN(date)
}

// 创建表记录
router.post('/table-data/:tableName', auth.authenticateToken, async (ctx) => {
  try {
    const { tableName } = ctx.params
    const data = ctx.request.body
    const userPermissions = ctx.state.user.permissions || []

    // 验证表名安全性
    if (!isValidTableName(tableName)) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '无效的表名'
      }
      return
    }

    const tableExists = await checkTableExists(tableName)
    if (!tableExists) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: `数据库表 ${tableName} 不存在`
      }
      return
    }

    // 检查创建权限 - 超级管理员跳过
    if (!userPermissions.includes('system:manage')) {
      const hasCreatePermission = await checkTablePermission(tableName, 'create', userPermissions)
      if (!hasCreatePermission) {
        ctx.status = 403
        ctx.body = {
          success: false,
          message: '您没有权限创建此数据表的记录'
        }
        return
      }
    }

    // 验证和清理输入数据
    const validatedData = await validateAndSanitizeData(tableName, data, 'create')
    if (!validatedData) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '数据验证失败'
      }
      return
    }

    // 构建插入查询
    const fields = Object.keys(validatedData).filter(key => key !== 'id')
    const values = fields.map(field => validatedData[field])
    const fieldPlaceholders = fields.map((_, index) => `:field${index}`).join(', ')
    const fieldNames = fields.map(field => `\`${field}\``).join(', ')
    
    const replacements = {}
    fields.forEach((field, index) => {
      replacements[`field${index}`] = validatedData[field]
    })
    
    const insertQuery = `INSERT INTO \`${tableName}\` (${fieldNames}) VALUES (${fieldPlaceholders})`
    
    const result = await sequelize.query(insertQuery, {
      replacements,
      type: sequelize.QueryTypes.INSERT
    })

    ctx.body = {
      success: true,
      data: { id: result[0], ...validatedData },
      message: '创建记录成功'
    }
  } catch (error) {
    console.error('创建表记录失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '创建记录失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    }
  }
})

// 更新表记录
router.put('/table-data/:tableName/:id', auth.authenticateToken, async (ctx) => {
  try {
    const { tableName, id } = ctx.params
    const data = ctx.request.body
    const userPermissions = ctx.state.user.permissions || []

    const tableExists = await checkTableExists(tableName)
    if (!tableExists) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: `数据库表 ${tableName} 不存在`
      }
      return
    }

    // 检查更新权限 - 超级管理员跳过
    console.log(`检查表 ${tableName} 的更新权限，用户权限:`, userPermissions)
    if (!userPermissions.includes('system:manage')) {
      const hasPermission = await checkTablePermission(tableName, 'update', userPermissions)
      console.log(`表 ${tableName} 更新权限检查结果:`, hasPermission)
      if (!hasPermission) {
        ctx.status = 403
        ctx.body = {
          success: false,
          message: '您没有权限更新此数据表的记录'
        }
        return
      }
    } else {
      console.log(`用户具有system:manage权限，跳过详细权限检查`)
    }

    // 验证和清理输入数据
    const validatedData = await validateAndSanitizeData(tableName, data, 'update')
    if (!validatedData) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '数据验证失败'
      }
      return
    }

    // 构建更新查询 - 排除系统字段
    const fields = Object.keys(validatedData).filter(key => 
      !['id', 'created_at', 'updated_at'].includes(key)
    )
    
    if (fields.length === 0) {
      ctx.status = 400
      ctx.body = {
        success: false,
        message: '没有可更新的字段'
      }
      return
    }
    
    const setClause = fields.map(field => `\`${field}\` = ?`).join(', ')
    const values = [...fields.map(field => validatedData[field]), id]
    
    // 添加更新时间
    const updateQuery = `UPDATE \`${tableName}\` SET ${setClause}, updated_at = NOW() WHERE id = ?`
    
    await sequelize.query(updateQuery, {
      replacements: values,
      type: sequelize.QueryTypes.UPDATE
    })

    ctx.body = {
      success: true,
      data: { id: parseInt(id), ...data },
      message: '更新记录成功'
    }
  } catch (error) {
    console.error('更新表记录失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '更新记录失败',
      error: error.message
    }
  }
})

// 删除表记录
router.delete('/table-data/:tableName/:id', auth.authenticateToken, async (ctx) => {
  try {
    const { tableName, id } = ctx.params
    const userPermissions = ctx.state.user.permissions || []

    const tableExists = await checkTableExists(tableName)
    if (!tableExists) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: `数据库表 ${tableName} 不存在`
      }
      return
    }

    // 检查删除权限 - 超级管理员跳过
    if (!userPermissions.includes('system:manage')) {
      const hasPermission = await checkTablePermission(tableName, 'delete', userPermissions)
      if (!hasPermission) {
        ctx.status = 403
        ctx.body = {
          success: false,
          message: '您没有权限删除此数据表的记录'
        }
        return
      }
    }

    // 执行删除
    const deleteQuery = `DELETE FROM ${tableName} WHERE id = ?`
    
    await sequelize.query(deleteQuery, {
      replacements: [id],
      type: sequelize.QueryTypes.DELETE
    })

    ctx.body = {
      success: true,
      message: '删除记录成功'
    }
  } catch (error) {
    console.error('删除表记录失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '删除记录失败',
      error: error.message
    }
  }
})

// 获取单条表记录
router.get('/table-data/:tableName/:id', auth.authenticateToken, async (ctx) => {
  try {
    const { tableName, id } = ctx.params
    const userPermissions = ctx.state.user.permissions || []

    const tableExists = await checkTableExists(tableName)
    if (!tableExists) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: `数据库表 ${tableName} 不存在`
      }
      return
    }

    // 检查用户是否有权限访问此表
    const menu = await DynamicMenu.findOne({ 
      where: { table_name: tableName, status: 'active' } 
    })
    
    if (menu && menu.permissions && menu.permissions.length > 0) {
      const hasReadPermission = menu.permissions.includes('read') && 
        userPermissions.some(perm => perm.includes('read') || perm === '*')
      if (!hasReadPermission) {
        ctx.status = 403
        ctx.body = {
          success: false,
          message: '您没有权限访问此数据表'
        }
        return
      }
    }

    // 查询单条记录
    const selectQuery = `SELECT * FROM ${tableName} WHERE id = ?`
    
    const result = await sequelize.query(selectQuery, {
      replacements: [id],
      type: sequelize.QueryTypes.SELECT
    })

    if (result.length === 0) {
      ctx.status = 404
      ctx.body = {
        success: false,
        message: '记录不存在'
      }
      return
    }

    ctx.body = {
      success: true,
      data: result[0],
      message: '获取记录成功'
    }
  } catch (error) {
    console.error('获取表记录失败:', error)
    ctx.status = 500
    ctx.body = {
      success: false,
      message: '获取记录失败',
      error: error.message
    }
  }
})

// 辅助函数：映射数据类型
function mapDataTypeToDisplayType(dataType) {
  const type = dataType.toLowerCase()
  if (type.includes('int') || type.includes('decimal') || type.includes('float') || type.includes('double')) {
    return 'number'
  }
  if (type.includes('date') || type.includes('time')) {
    return 'date'
  }
  if (type.includes('text') || type.includes('json')) {
    return 'text'
  }
  return 'string'
}

module.exports = router
